package com.yqg.manage.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yqg.manage.entity.Place;
import com.yqg.manage.entity.PlaceAccount;
import com.yqg.manage.mapper.PlaceAccountMapper;
import com.yqg.manage.mapper.PlaceMapper;
import com.yqg.manage.service.IPlaceAccountService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yqg.manage.service.IPlaceService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * PlaceAccountServiceImpl 服务实现类
 *
 * @author zxf
 * @since 2025-08-26
 */
@Service
public class PlaceAccountServiceImpl extends ServiceImpl<PlaceAccountMapper, PlaceAccount> implements IPlaceAccountService {
    @Resource
    private IPlaceService placeService;

    @Resource
    private PlaceAccountMapper placeAccountMapper;

    @Override
    public PlaceAccount preStorageProcessing(PlaceAccount placeAccount) {
        if (placeAccount.getId() == null) {
            placeAccount.setPassword(SecureUtil.md5("123456"));
        }
        // 判断账户名是否被占用
        LambdaQueryWrapper<PlaceAccount> placeAccountWrapper = new LambdaQueryWrapper<>();
        placeAccountWrapper.eq(PlaceAccount::getName,placeAccount.getName())
                .eq(PlaceAccount::getIsDelete, "0");
        PlaceAccount account = getOne(placeAccountWrapper);
        if (account != null && !account.getId().equals(placeAccount.getId())) {
            return null;
        }

        LambdaQueryWrapper<Place> placeWrapper = new LambdaQueryWrapper<>();
        placeWrapper.eq(Place::getCompanyLicense, placeAccount.getCompanyLicense())
                .eq(Place::getIsDelete, "0");
        Place one = placeService.getOne(placeWrapper);
        if (one == null) {
            // 商户不存在，新增直接绑定
            one = new Place();
            one.setCompanyName(placeAccount.getCompanyName());
            one.setCompanyLicense(placeAccount.getCompanyLicense());
            one.setEnterpriseType(placeAccount.getEnterpriseType());
            placeService.save(one);
            placeAccount.setPlaceId(one.getId());
        } else {
            // 商户存在，看其是否绑定账号
            LambdaQueryWrapper<PlaceAccount> placeAccountLambdaQueryWrapper = new LambdaQueryWrapper<>();
            placeAccountLambdaQueryWrapper.eq(PlaceAccount::getPlaceId, one.getId())
                    .eq(PlaceAccount::getIsDelete, "0");
            PlaceAccount placeAccount1 = getOne(placeAccountLambdaQueryWrapper);
            if (placeAccount1 == null){
                // 未绑定账户，直接绑定
                placeAccount.setPlaceId(one.getId());
            }else{
                if(!placeAccount1.getPlaceId().equals(placeAccount.getPlaceId())) {
                    // 已被其他账户绑定
                    placeAccount.setPlaceId(null);
                }
            }
        }
        return placeAccount;
    }
}
